var common = require('../../utils/mr_xu/common.js')

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    time: {
      type: String,
      value: '',
    },
    type: {
      type: String,
      value: '',
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    countDownNum: '60',//倒计时初始值
    countDownStr: '',
    startTimeStr: '',
    config_time_limit:''
  },
  attached() {
    this.setData({
      startTimeStr: this.properties.time
    })
    this.setConfig()
    this.countDown(this.data.startTimeStr)
  },
  /**
   * 组件的方法列表
   */
  methods: {
    setConfig() {

      let settings = wx.getStorageSync('settings')
      let item = ''
      if (this.data.type == 'quest_pay') {
        item = 'QUEST_PAY_TIME'
      } else {
        item = 'QUEST_DIFFERENCE_TIME'
      }
      for (let i in settings) {
        if (settings[i].key == item) {
          this.setData({
            config_time_limit: settings[i].value
          })
          
          break
        }
       
      }
    },
    countDown: function (timeStr) {
      let that = this;
      var now = parseInt(Date.parse(new Date()) / 1000)
      var limit = common.strtotime(timeStr) + that.data.config_time_limit * 3600 - now
      if (limit <= 0) {
        console.log('传参错误，倒计时已经结束')
        return
      }
      that.setData({
        countDownNum: limit
      })
  
      let countDownNum = that.data.countDownNum;//获取倒计时初始值
      //如果将定时器设置在外面，那么用户就看不到countDownNum的数值动态变化，所以要把定时器存进data里面
      that.setData({
        timer: setInterval(function () {//这里把setInterval赋值给变量名为timer的变量

          //在倒计时还未到0时，这中间可以做其他的事情，按项目需求来
          if (countDownNum == 0) {
            //这里特别要注意，计时器是始终一直在走的，如果你的时间为0，那么就要关掉定时器！不然相当耗性能
            //因为timer是存在data里面的，所以在关掉时，也要在data里取出后再关闭
            clearInterval(that.data.timer);
            //关闭定时器之后，可作其他处理codes go here
            that.setData({
              countDownStr:'倒计时已结束'
            })
            return
          }

          //每隔一秒countDownNum就减一，实现同步
          countDownNum--;
          //然后把countDownNum存进data，好让用户知道时间在倒计着
          that.setData({
            countDownNum: countDownNum,
            countDownStr: that.formatCountDownTime(countDownNum)
          })
          
        }, 1000)
      })
    },
    formatCountDownTime(seconds) {

      let leftSeconds = seconds

      let hour = Math.floor(leftSeconds / 3600)
      leftSeconds -= hour * 3600

      let minute = Math.floor(leftSeconds / 60)
      leftSeconds -= minute * 60

      return ("0" + hour).substr(-2) + ':' + ("0" + minute).substr(-2) + ':' + ("0" + leftSeconds).substr(-2);
    },
  }
})
